package ink.ykb.demo.user.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import ink.ykb.demo.config.CodeConstant;
import ink.ykb.demo.config.Constant;
import ink.ykb.demo.config.MessageUtil;
import ink.ykb.demo.config.ServiceException;
import ink.ykb.demo.permission.entity.DealerDepartment;
import ink.ykb.demo.permission.entity.Role;
import ink.ykb.demo.permission.entity.Rule;
import ink.ykb.demo.permission.entity.UserDealerDepartment;
import ink.ykb.demo.permission.enums.DepartDataScope;
import ink.ykb.demo.permission.enums.RuleType;
import ink.ykb.demo.permission.service.DealerDepartmentService;
import ink.ykb.demo.permission.service.RuleService;
import ink.ykb.demo.permission.service.UserDealerDepartmentService;
import ink.ykb.demo.permission.service.UserRoleService;
import ink.ykb.demo.permission.service.dto.UserPermissionInfo;
import ink.ykb.demo.user.dao.UserLoginLogDao;
import ink.ykb.demo.user.entity.UserInfo;
import ink.ykb.demo.user.entity.UserLoginLog;
import ink.ykb.demo.util.PwdUtil;
import ink.ykb.demo.util.WebUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private MessageUtil messageUtil;
	@Value("${project.debug}")
	private Boolean debug;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private UserLoginLogDao userLoginLogDao;
	@Autowired
	private DealerDepartmentService dealerDepartmentService;
	@Autowired
	private UserDealerDepartmentService userDealerDepartmentService;
	@Autowired
	private RuleService ruleService;
	

	@Override
	public UserInfo getCurrentUserInfo() {
		UserInfo userInfo = this.getCurrentUserInfoNoCheck();
		if (userInfo == null) {
			throw new ServiceException(CodeConstant.USER_EMPTY, messageUtil.getMsg(CodeConstant.USER_EMPTY));
		}
		return userInfo;
	}

	@Override
	public UserInfo getCurrentUserInfoNoCheck() {
		if (true == debug) {// 测试使用 TODO
			UserInfo userInfo = userInfoService.getUserInfo(1L);
			return userInfo;
		}

		Long userId = this.getCurrentUserIdNoCheck();
		if (userId == null) {
			return null;
		}

		UserInfo userInfo = userInfoService.getUserInfo(userId);
		return userInfo;
	}

	@Override
	public Long getCurrentUserId() {

		Long userId = this.getCurrentUserIdNoCheck();
		if (userId == null) {
			throw new ServiceException(CodeConstant.TOKEN_EMPTY, messageUtil.getMsg(CodeConstant.TOKEN_EMPTY));
		}

		return userId;
	}

	@Override
	public Long getCurrentUserIdNoCheck() {
		if (true == debug) {// 测试使用 TODO
			return 1L;
		}
		String userToken = this.getCurrentUserToken();
		Object idObject = redisTemplate.opsForValue().get(Constant.USER_ID_KEY_PREFIX + userToken);
		if (idObject == null) {
			return null;
		}
		return Long.valueOf(idObject.toString());
	}

	@Override
	public UserPermissionInfo getCurrentUserPermissionInfo() {
		if (true == debug) {// 测试使用 TODO
			UserPermissionInfo info = new UserPermissionInfo();
			List<Role> set = new ArrayList<>();
			Role role = new Role();
			role.setCode(Constant.SUPER_ADMIN_RULE_CODE);
			role.setName("超级管理员");
			set.add(role);
			info.setRoles(set);
			return info;
		}

		Long userId = this.getCurrentUserId();
		return this.getUserPermissionInfo(userId);
	}

	@Override
	public UserPermissionInfo getUserPermissionInfo(Long userId) {
		UserPermissionInfo info = new UserPermissionInfo();
		List<Role> userRoleList = userRoleService.getUserRoleList(userId);
		List<Rule> userRuleSet = userRoleService.getUserRuleList(userId);
		info.setRoles(userRoleList);
		info.setRules(userRuleSet);

		return info;
	}

	@Override
	public String getCurrentUserToken() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		if (request != null) {
			String token = request.getHeader(Constant.USER_TOKEN_KEY);
			if (token == null || token == "") {
				token = request.getParameter(Constant.USER_TOKEN_KEY);
			}
			if (token == null || token == "") {
				token = request.getParameter(Constant.USER_TOKEN_KEY.toLowerCase());// 转小写
			}

			return token;
		}
		return null;
	}

	@Override
	public String login(String userName, String password) {
		if (StringUtils.isBlank(userName)) {
			throw new ServiceException(CodeConstant.USER_NAME_EMPTY, messageUtil.getMsg(CodeConstant.USER_NAME_EMPTY));
		}
		if (StringUtils.isBlank(password)) {
			throw new ServiceException(CodeConstant.PASSWORD_EMPTY, messageUtil.getMsg(CodeConstant.PASSWORD_EMPTY));
		}
		UserInfo userInfo = userInfoService.getUserInfo(userName);
		if (userInfo == null) {
			throw new ServiceException(CodeConstant.USER_EMPTY, messageUtil.getMsg(CodeConstant.USER_EMPTY));
		}

		if (!PwdUtil.validateHash(password, userInfo.getPassword())) {
			throw new ServiceException(CodeConstant.PASSWORD_ERROR, messageUtil.getMsg(CodeConstant.PASSWORD_ERROR));
		}

		String token = UUID.randomUUID().toString();

		UserLoginLog userLoginLog = new UserLoginLog();
		userLoginLog.setToken(token);
		userLoginLog.setUserId(userInfo.getId());

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		if (request != null) {
			userLoginLog.setUserAgent(WebUtil.getUserAgent(request));
			userLoginLog.setIp(WebUtil.getIPAddress(request));
		}

		userLoginLog.setCreateTime(new Date());
		userLoginLogDao.insert(userLoginLog);

		redisTemplate.opsForValue().set(Constant.USER_ID_KEY_PREFIX + token, userInfo.getId(), 1, TimeUnit.DAYS);// 缓存1天
		
		log.info("userToken:{}", token);
		return token;
	}

	@Override
	public List<Rule> getUserMenu() {
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		
		List<Rule> userRuleList = null;
		if(isSuperAdmin) {//超级管理员查询所有菜单
			userRuleList = ruleService.getRuleList(RuleType.MENU.getValue());
		}else {
			userRuleList = userRoleService.getUserRuleList(userId,RuleType.MENU.getValue());
		}
		
		if(userRuleList == null || userRuleList.size() == 0) {
			return new ArrayList<>();
		}
		
	    List<Rule> ruleTree = this.getRuleTree(userRuleList,0L);
	    
	    //判断是否查询根菜单
	    if(ruleTree == null || ruleTree.size() == 0) {
	    	throw new ServiceException(CodeConstant.MUS_109, messageUtil.getMsg(CodeConstant.MUS_109));
	    }
	    
		return ruleTree;
	}
	
	@Override
	public boolean isSuperAdmin(Long userId) {
		
		List<Role> userRoleList = userRoleService.getUserRoleList(userId);
		for (Role role : userRoleList) {
			if(role.getCode().equalsIgnoreCase(Constant.SUPER_ADMIN_RULE_CODE)) {
				return true;
			}
		}
		
		return false;
	}
	
	@Override
	public boolean isSuperAdmin(List<Role> userRoleList) {
		
		for (Role role : userRoleList) {
			if(role.getCode().equalsIgnoreCase(Constant.SUPER_ADMIN_RULE_CODE)) {
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 根据已有数据集，根据父级菜单递归查找子级菜案
	 * @param ruleList
	 * @param parentId
	 * @return
	 */
	private List<Rule> getRuleTree(List<Rule> ruleList,Long parentId) {
		List<Rule> result = this.getRuleListByParentId(ruleList,parentId);
		for (Rule rule : result) {
			List<Rule> list = this.getRuleTree(ruleList,rule.getId());
			if (list != null && list.size() > 0) {
				rule.setChilds(list);
			}
		}

		return result;
	}
	
	/**
	 * 根据已有数据集查询父级对应的子集数据
	 * @param userRuleList
	 * @param parentId
	 * @return
	 */
	private List<Rule> getRuleListByParentId(List<Rule> ruleList,Long parentId){
		List<Rule> list = new ArrayList<>();
		if(ruleList == null || ruleList.size() == 0) {
			return list;
		}
		for (Rule rule : ruleList) {
			if(parentId.equals(rule.getParentId())) {
				list.add(rule);
			}
		}
		return list;
	}
	
	@Transactional
	@Override
	public void addDealerDepartment(DealerDepartment dealerDepartment) {
		if(dealerDepartment.getParentId() == null) {
			dealerDepartment.setParentId(0L);
		}
		
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		if(isSuperAdmin) {//如果为超级管理员
			dealerDepartmentService.add(dealerDepartment);
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//权限判断
		boolean isAccess = this.hasDoDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), dealerDepartment.getParentId());
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		dealerDepartmentService.add(dealerDepartment);
		
	}
	
	@Transactional
	@Override
	public void updateDealerDepartment(DealerDepartment dealerDepartment) {
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		if(isSuperAdmin) {//如果为超级管理员
			dealerDepartmentService.update(dealerDepartment);
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//权限判断
		boolean isAccess = this.hasDoDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), dealerDepartment.getParentId());
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		dealerDepartmentService.update(dealerDepartment);
		
	}
	
	
	@Transactional
	@Override
	public void deleteDealerDepartment(Long dealerDepartmentId) {
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		if(isSuperAdmin) {//如果为超级管理员
			dealerDepartmentService.delete(dealerDepartmentId);
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//权限判断
		//查询
		DealerDepartment dbDealerDepartment = dealerDepartmentService.getDealerDepartment(dealerDepartmentId);
		if (dbDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_111, messageUtil.getMsg(CodeConstant.MUS_111));
		}
		
		//权限判断
		boolean isAccess = this.hasDoDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), dbDealerDepartment.getParentId());
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		dealerDepartmentService.delete(dealerDepartmentId);		
		
	}
	
	@Transactional
	@Override
	public void addUserDealerDepartment(Long dealerDepartmentId, Long userId,Integer scope) {
		//获取用户ID
		Long currentUserId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(currentUserId);
		if(isSuperAdmin) {//如果为超级管理员
			UserDealerDepartment userDealerDepartment = new UserDealerDepartment();
			userDealerDepartment.setDealerDepartmentId(dealerDepartmentId);
			userDealerDepartment.setUserId(userId);
			userDealerDepartment.setScope(scope);
			userDealerDepartmentService.add(userDealerDepartment);
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(currentUserId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//查询
		DealerDepartment dbDealerDepartment = dealerDepartmentService.getDealerDepartment(dealerDepartmentId);
		if (dbDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_111, messageUtil.getMsg(CodeConstant.MUS_111));
		}
		
		//权限判断
		boolean isAccess = this.hasDoUserDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), dealerDepartmentId,scope);
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		UserDealerDepartment udd = new UserDealerDepartment();
		udd.setDealerDepartmentId(dealerDepartmentId);
		udd.setUserId(userId);
		udd.setScope(scope);
		userDealerDepartmentService.add(udd);
	}

	@Transactional
	@Override
	public void updateUserDealerDepartment(Long dealerDepartmentId, Long userId,Integer scope) {
		//获取用户ID
		Long currentUserId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(currentUserId);
		if(isSuperAdmin) {//如果为超级管理员
			userDealerDepartmentService.update(userId, dealerDepartmentId,scope);
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(currentUserId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//查询
		DealerDepartment dbDealerDepartment = dealerDepartmentService.getDealerDepartment(dealerDepartmentId);
		if (dbDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_111, messageUtil.getMsg(CodeConstant.MUS_111));
		}
		
		//权限判断
		boolean isAccess = this.hasDoUserDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), 
				dealerDepartmentId,scope);
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		//判断修改用户的部门的在当前用户可查看的部门范围内
		UserDealerDepartment byUserId = userDealerDepartmentService.getByUserId(userId);
		isAccess = this.hasDoDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), byUserId.getDealerDepartmentId());
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		userDealerDepartmentService.update(userId, dealerDepartmentId,scope);
	}

	@Transactional
	@Override
	public void deleteUserDealerDepartment(Long userId) {
		//获取用户ID
		Long currentUserId = this.getCurrentUserId();
		
		//查询
		UserDealerDepartment dbUserDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if (dbUserDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(currentUserId);
		if(isSuperAdmin) {//如果为超级管理员
			userDealerDepartmentService.delete(dbUserDealerDepartment.getId());
			return;
		}
		
		//如果不是超级管理员
		
		//获取当前用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(currentUserId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		//权限判断
		boolean isAccess = this.hasDoUserDealerDepartmentPermission(
				userDealerDepartment.getDealerDepartmentId(), userDealerDepartment.getScope(), 
				dbUserDealerDepartment.getDealerDepartmentId(),dbUserDealerDepartment.getScope());
		if(!isAccess) {
			throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
		}
		
		userDealerDepartmentService.delete(dbUserDealerDepartment.getId());
		
	}
	
	@Override
	public boolean hasDoDealerDepartmentPermission(Long parentId,Integer parentScope,Long childId) {
		DepartDataScope scope = DepartDataScope.getType(parentScope);
		if(scope == DepartDataScope.LEVEL_1 || scope == DepartDataScope.LEVEL_2) {
			return false;
		}else if(scope == DepartDataScope.LEVEL_3 || scope == DepartDataScope.LEVEL_4) {
			//判断此添加部门的父级部门是否在用户的可查询部门范围内
			List<DealerDepartment> userDealerDepartmentTreeList = new ArrayList<>();
			List<DealerDepartment> userDealerDepartmentList = new ArrayList<>();
			DealerDepartment depart = dealerDepartmentService.getDealerDepartment(parentId);
			userDealerDepartmentTreeList.add(depart);
			List<DealerDepartment> childs = dealerDepartmentService.getDealerDepartmentTree(parentId);
			userDealerDepartmentTreeList.addAll(childs);
			
			for (DealerDepartment dd : userDealerDepartmentTreeList) {
				userDealerDepartmentList.addAll(dealerDepartmentService.getAllByTree(dd));
			}

			boolean isAccess = false;
			for (DealerDepartment dd : userDealerDepartmentList) {
				if(dd.getId().equals(childId)) {
					isAccess = true;
					break;
				}
			}
			return isAccess;
		}
		return false;
	}
	
	@Override
	public boolean hasDoUserDealerDepartmentPermission(
			Long parentId,Integer parentScope,Long childId,Integer childScope) {
		DepartDataScope scope = DepartDataScope.getType(parentScope);
		if(scope == DepartDataScope.LEVEL_1) {
			return false;
		}else if(scope == DepartDataScope.LEVEL_2) {
			if(parentId.equals(childId)) {
				if(DepartDataScope.getType(childScope) == DepartDataScope.LEVEL_1 || DepartDataScope.getType(childScope) == DepartDataScope.LEVEL_2) {
					return true;
				}
			}
			return false;
		}else if(scope == DepartDataScope.LEVEL_3 || scope == DepartDataScope.LEVEL_4) {
			
			//判断此添加部门的父级部门是否在用户的可查询部门范围内
			List<DealerDepartment> userDealerDepartmentTreeList = new ArrayList<>();
			List<DealerDepartment> userDealerDepartmentList = new ArrayList<>();
			 if(scope == DepartDataScope.LEVEL_4) {
				 DealerDepartment depart = dealerDepartmentService.getDealerDepartment(parentId);
				 userDealerDepartmentTreeList.add(depart);
			 }
			
			List<DealerDepartment> childs = dealerDepartmentService.getDealerDepartmentTree(parentId);
			userDealerDepartmentTreeList.addAll(childs);
			
			for (DealerDepartment dd : userDealerDepartmentTreeList) {
				userDealerDepartmentList.addAll(dealerDepartmentService.getAllByTree(dd));
			}
			
			boolean isAccess = false;
			for (DealerDepartment dd : userDealerDepartmentList) {
				if(dd.getId().equals(childId)) {
					isAccess = true;
					break;
				}
			}
			return isAccess;
		}
		return false;
	}

	@Override
	public List<DealerDepartment> getUserDealerDepartmentTree() {
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		if(isSuperAdmin) {//如果为超级管理员
			//查询所有根部门
			List<DealerDepartment> rootList = dealerDepartmentService.getDealerDepartmentTree(0L);
			return rootList;
		}
		
		//如果不是超级管理员
			
		//获取用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		
		//查询用户的部门的经销商部门树
		List<DealerDepartment> rootList = new ArrayList<>();
		
		DepartDataScope scope = DepartDataScope.getType(userDealerDepartment.getScope());
		if(scope == DepartDataScope.LEVEL_1 || scope == DepartDataScope.LEVEL_2) {
			DealerDepartment rootTree = dealerDepartmentService.getDealerDepartmentTreeToRoot(userDealerDepartment.getDealerDepartmentId());
			rootList.add(rootTree);
		}else if(scope == DepartDataScope.LEVEL_3 || scope == DepartDataScope.LEVEL_4) {
			DealerDepartment rootTree = dealerDepartmentService.getDealerDepartmentTreeByRoot(userDealerDepartment.getDealerDepartmentId());
			rootList.add(rootTree);
		}		
		
		return rootList;
		
	}

	@Override
	public List<DealerDepartment> getUserDealerDepartmentPermission() {
				//获取用户ID
				Long userId = this.getCurrentUserId();
				
				//判断用户是否为超级管理员
				boolean isSuperAdmin = this.isSuperAdmin(userId);
				if(isSuperAdmin) {//如果为超级管理员
					List<DealerDepartment> data = new ArrayList<>();
					
					//查询所有根部门
					List<DealerDepartment> rootList = dealerDepartmentService.getDealerDepartmentTree(0L);
					for (DealerDepartment dd : rootList) {
						data.addAll(dealerDepartmentService.getAllByTree(dd));
					}
					return data;
				}
				
				//如果不是超级管理员
					
				//获取用户的部门
				UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
				if(userDealerDepartment == null) {
					throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
				}
				
				List<DealerDepartment> data = new ArrayList<>();
				//查询用户的部门的经销商部门树
				List<DealerDepartment> rootList = new ArrayList<>();
				
				DepartDataScope scope = DepartDataScope.getType(userDealerDepartment.getScope());
				if(scope == DepartDataScope.LEVEL_1 || scope == DepartDataScope.LEVEL_2) {
					DealerDepartment dd = dealerDepartmentService.getDealerDepartment(userDealerDepartment.getDealerDepartmentId());
					rootList.add(dd);
				}else if(scope == DepartDataScope.LEVEL_3 || scope == DepartDataScope.LEVEL_4) {
					DealerDepartment dd = dealerDepartmentService.getDealerDepartment(userDealerDepartment.getDealerDepartmentId());
					rootList.add(dd);
					
					List<DealerDepartment> childs = dealerDepartmentService.getDealerDepartmentTree(userDealerDepartment.getDealerDepartmentId());
					rootList.addAll(childs);
				}		
				
				for (DealerDepartment dd : rootList) {
					data.addAll(dealerDepartmentService.getAllByTree(dd));
				}
				return data;
	}
	
	@Override
	public List<UserDealerDepartment> getUsersByDealerDepartmentPermission() {
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		
		if(isSuperAdmin) {//如果为超级管理员
			//查询所有根部门
			List<DealerDepartment> rootList = dealerDepartmentService.getByParentId(0L);
			
			List<UserDealerDepartment> userDealerDepartmentList = new ArrayList<>();
			
			for (DealerDepartment dd : rootList) {
				List<UserDealerDepartment> userDealerDepartmentTree = 
						userDealerDepartmentService.getUserDealerDepartmentAll(dd.getId());
				userDealerDepartmentList.addAll(userDealerDepartmentTree);
			}
			
			return userDealerDepartmentList;
			
		}
		
		//如果不是超级管理员
		//获取用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		
		List<UserDealerDepartment>  data = new ArrayList<>();
		DepartDataScope scope = DepartDataScope.getType(userDealerDepartment.getScope());
		if(scope == DepartDataScope.LEVEL_1) {
			data.add(userDealerDepartment);
		}else if(scope == DepartDataScope.LEVEL_2) {
			List<UserDealerDepartment> users = userDealerDepartmentService.getByDealerDepartmentId(
					userDealerDepartment.getDealerDepartmentId());
			data.addAll(users);
		}else if(scope == DepartDataScope.LEVEL_3) {
			data.add(userDealerDepartment);
			
			List<DealerDepartment> childs = dealerDepartmentService.getByParentId(userDealerDepartment.getDealerDepartmentId());
			for (DealerDepartment dealerDepartment : childs) {
				List<UserDealerDepartment> childListByTree = userDealerDepartmentService
						.getUserDealerDepartmentAll(dealerDepartment.getId());
				data.addAll(childListByTree);
			}
			
		}else if(scope == DepartDataScope.LEVEL_4) {
			List<UserDealerDepartment> users = userDealerDepartmentService
					.getByDealerDepartmentId(userDealerDepartment.getDealerDepartmentId());
			data.addAll(users);
			
			List<DealerDepartment> childs = dealerDepartmentService.getByParentId(userDealerDepartment.getDealerDepartmentId());
			for (DealerDepartment dealerDepartment : childs) {
				List<UserDealerDepartment> childListByTree = userDealerDepartmentService
						.getUserDealerDepartmentAll(dealerDepartment.getId());
				data.addAll(childListByTree);
			}
		}
			
		return data;
	}
	
	@Override
	public List<UserDealerDepartment> getUsersByDealerDepartmentPermission(Long dealerDepartmentId){
		//获取用户ID
		Long userId = this.getCurrentUserId();
		
		//判断用户是否为超级管理员
		boolean isSuperAdmin = this.isSuperAdmin(userId);
		if(isSuperAdmin) {//如果为超级管理员
			List<UserDealerDepartment>  data = userDealerDepartmentService.getByDealerDepartmentId(dealerDepartmentId);
			return data;
		}
		
		//如果不是超级管理员
		
		List<UserDealerDepartment>  data = new ArrayList<>();
		//获取用户的部门
		UserDealerDepartment userDealerDepartment = userDealerDepartmentService.getByUserId(userId);
		if(userDealerDepartment == null) {
			throw new ServiceException(CodeConstant.MUS_113, messageUtil.getMsg(CodeConstant.MUS_113));
		}
		
		DepartDataScope scope = DepartDataScope.getType(userDealerDepartment.getScope());
		if(scope == DepartDataScope.LEVEL_1) {
			if(!dealerDepartmentId.equals(userDealerDepartment.getDealerDepartmentId())) {
				throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
			}
			data.add(userDealerDepartment);
		}else if(scope == DepartDataScope.LEVEL_2) {
			if(!dealerDepartmentId.equals(userDealerDepartment.getDealerDepartmentId())) {
				throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
			}
			List<UserDealerDepartment> users = userDealerDepartmentService.getByDealerDepartmentId(dealerDepartmentId);
			data.addAll(users);
		}else if(scope == DepartDataScope.LEVEL_3) {
			//判断此部门是否有权限查询
			List<DealerDepartment> userDealerDepartmentTreeList = new ArrayList<>();
			List<DealerDepartment> userDealerDepartmentList = new ArrayList<>();
			DealerDepartment dealerDepartment = dealerDepartmentService.getDealerDepartment(userDealerDepartment.getDealerDepartmentId());
			userDealerDepartmentTreeList.add(dealerDepartment);
			List<DealerDepartment> childs = dealerDepartmentService.getDealerDepartmentTree(userDealerDepartment.getDealerDepartmentId());
			userDealerDepartmentTreeList.addAll(childs);
			
			for (DealerDepartment dd : userDealerDepartmentTreeList) {
				userDealerDepartmentList.addAll(dealerDepartmentService.getAllByTree(dd));
			}
			boolean isAccess = false;
			for (DealerDepartment dd : userDealerDepartmentList) {
				if(dd.getId().equals(dealerDepartmentId)) {
					isAccess = true;
					break;
				}
			}
			if(!isAccess) {
				throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
			}
			
			if(dealerDepartmentId.equals(userDealerDepartment.getDealerDepartmentId())) {
				data.add(userDealerDepartment);
			}else {
				List<UserDealerDepartment> users = userDealerDepartmentService.getByDealerDepartmentId(dealerDepartmentId);
				data.addAll(users);
			}
			
		}else if(scope == DepartDataScope.LEVEL_4) {
			//判断此部门是否有权限查询
			List<DealerDepartment> userDealerDepartmentTreeList = new ArrayList<>();
			List<DealerDepartment> userDealerDepartmentList = new ArrayList<>();
			DealerDepartment dealerDepartment = dealerDepartmentService.getDealerDepartment(userDealerDepartment.getDealerDepartmentId());
			userDealerDepartmentTreeList.add(dealerDepartment);
			List<DealerDepartment> childs = dealerDepartmentService.getDealerDepartmentTree(userDealerDepartment.getDealerDepartmentId());
			userDealerDepartmentTreeList.addAll(childs);
			
			for (DealerDepartment dd : userDealerDepartmentTreeList) {
				userDealerDepartmentList.addAll(dealerDepartmentService.getAllByTree(dd));
			}
			boolean isAccess = false;
			for (DealerDepartment dd : userDealerDepartmentList) {
				if(dd.getId().equals(dealerDepartmentId)) {
					isAccess = true;
					break;
				}
			}
			if(!isAccess) {
				throw new ServiceException(CodeConstant.ACCESS_DENIED, messageUtil.getMsg(CodeConstant.ACCESS_DENIED));
			}
			
			List<UserDealerDepartment> users = userDealerDepartmentService.getByDealerDepartmentId(dealerDepartmentId);
			data.addAll(users);
		}
			
		return data;
		
	}


}
